package com.wangfei.lecture.SM;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.util.encoders.Hex;

public class Test {
    public static void  main(String[] args) {
//        String str2 = sortMapToSTring(map);
//        System.out.println("待验签字符串：" + str2);
//        String signature = (String) respMap.get("signature");

        String sortedString = "123456789";
        SMUtil smUtil = new SMUtil();
        String pubkey = "044b214b8a5508c82974165b722199002634ef16c2e66b10c42656cf68629a63174031da6f52ea4af3fe254ddb4e38b433aa6ae95cde849c94d7fb659159af07e9";
        String prikey = "00e756a79f96f386da644febaed225283c616a7e2257d73cbe2caf41fa54bb3fe9";
        byte[] result = smUtil.sm2Sign(prikey, sortedString);
        System.out.println(Base64.encodeBase64String(result));
        System.out.println(SMUtil.sm2SignValidate(pubkey, result, sortedString));


        ByteKeyPair byteKeyPair = SM2Key.generateSm2Keys();
        String stirngHex = Hex.toHexString(byteKeyPair.getSm2PublicKeyBytes());
        System.out.println(Hex.toHexString(byteKeyPair.getSm2PrivateBytes()));
        System.out.println(stirngHex);

        String base64String = "BH3IcpwFiEfh67frNcW2gJGffaFHkvnzJpht9t1KI6LZO6IpOeMp6WYmCau9Agrecjj71if+08kb12EXPe+BBDw=";
//        String hexString = Hex.toHexString(Base64.decode(base64String));
//        String pemStr = SM2Key.hexSm2PublicKeyToPem(hexString);
//        System.out.println("pemStr: " + pemStr);

        String prodPri = "00e756a79f96f386da644febaed225283c616a7e2257d73cbe2caf41fa54bb3fe9";
        String prodPub = "044b214b8a5508c82974165b722199002634ef16c2e66b10c42656cf68629a63174031da6f52ea4af3fe254ddb4e38b433aa6ae95cde849c94d7fb659159af07e9";
        System.out.println("pubkey's file: " + hexSm2PublicKeyToPem(prodPub));
//        System.out.println("prikey's file: " + hexSm2PublicKeyToPem(prodPub));


//        prodPub = "044b214b8a5508c82974165b722199002634ef16c2e66b10c42656cf68629a63174031da6f52ea4af3fe254ddb4e38b433aa6ae95cde849c94d7fb659159af07e9";
//        prodPri = "00e756a79f96f386da644febaed225283c616a7e2257d73cbe2caf41fa54bb3fe9";
//        String signature = Base64.encodeBase64String(SMUtil.sm2Sign(prodPri,"appId=1888666&cardCount=1&cardList=accountLevel=99&accountMedia=4&areaCode=0000&cardAttr=01&cardNo=6236 **** 6602&cardSt=02&extensions=null&issInsIdCd=null&reserveMobile=null&extensions=null&msg=成功&nonceStr=fc31a1ee226ee4cd&registerMobile=null&resp=00&symmetricKey=79c8bc701bc7c9ae&timestamp=1663223146815&userId=null"));
//        System.out.println(signature);
//        System.out.println(SMUtil.sm2SignValidate(prodPub,Base64.decodeBase64(signature),"appId=1888666&cardCount=1&cardList=accountLevel=99&accountMedia=4&areaCode=0000&cardAttr=01&cardNo=6236 **** 6602&cardSt=02&extensions=null&issInsIdCd=null&reserveMobile=null&extensions=null&msg=成功&nonceStr=fc31a1ee226ee4cd&registerMobile=null&resp=00&symmetricKey=79c8bc701bc7c9ae&timestamp=1663223146815&userId=null"));

//        prodPub = "af0ea01e61236c863009b4174d1ec550de327db602ae49a29ebaa4c2583e6443bac6735f06888d4516484d5bfc575ee7f5e8b6dd7f5bdc0d172b2568148a2f2e";
//        System.out.println(Hex.toHexString(SMUtil.sm2Encrypt(prodPub, "12345abcde")));
//        System.out.println(Base64.getEncoder().encodeToString(Hex.decode(stirngHex)));
//        String publicKey = "af0ea01e61236c863009b4174d1ec550de327db602ae49a29ebaa4c2583e6443bac6735f06888d4516484d5bfc575ee7f5e8b6dd7f5bdc0d172b2568148a2f2e";
//        String privateKey = "9db5db4c74141ab033132c1eb11ed6a5c77c0f7652df0715a6735d606a61fce5";
//
//        byte[] encryptBytes = SMUtil.sm2Encrypt(publicKey, "12345abcde");
//        System.out.println("result: " + Hex.toHexString(encryptBytes));

//        System.out.println(Base64.getEncoder().encodeToString(SMUtil.sm2Sign(prodPri, "wangfei")));
//        String base64Str = Base64.toBase64String(SMUtil.sm2Encrypt(prodPub,"wangfei"));
//        System.out.println("base64Str: " + base64Str);
//        System.out.println(SMUtil.sm2Decrypt(prodPri, org.apache.tomcat.util.codec.binary.Base64.decodeBase64(base64Str)));
//        HashMap<String, String> map = new HashMap<>();

    }

    /**
     * hex格式公钥转换成pem格式公钥
     * @param hexPublicKey
     * @return
     */
    public static String hexSm2PublicKeyToPem(String hexPublicKey){
        //补充硬加密的头
        String hexHead="3059301306072a8648ce3d020106082a811ccf5501822d034200";
        String hexKey = hexHead+hexPublicKey.replaceAll(" ","");
        //两个拼起来转base64
        String base64Fulfill = Base64.encodeBase64String(Hex.decode(hexKey));
        String sm2PemKey = "-----BEGIN PUBLIC KEY-----"+base64Fulfill+"-----END PUBLIC KEY-----";
        return sm2PemKey;
    }

//    public String importCertAndPrivateKeyPEM(String sm2PublicKeyPEMFilepath, String sm2PrivateKeyPEMFilepath, char[] priKeyPassword, String alias)
//    {
//        InputStream bis1 = null;
//        InputStream bis2 = null;
//        X509Certificate cert = null;
//        try
//        {
//            bis1 = new FileInputStream(new File(sm2PublicKeyPEMFilepath));
//            CertificateFactory cf = CertificateFactory.getInstance("X509", DoubleCA.PROVIDER_NAME);
//            cert = (X509Certificate)cf.generateCertificate(bis1);
//            if (alias == null)
//            {
//                alias = DnComponents.stringToBCDNString(((X509Certificate)cert).getSubjectDN().getName());
//            }
//            PublicKey sm2PublicKey = cert.getPublicKey();
//
//            bis2 = new FileInputStream(new File(sm2PrivateKeyPEMFilepath));
//            int bufferLen = bis2.available();
//            byte[] bufferTemp = new byte[bufferLen];
//            bis2.read(bufferTemp);
//            String strtemp = new String(bufferTemp);
//            strtemp = strtemp.replaceAll("-----BEGIN PRIVATE KEY-----", "");
//            strtemp = strtemp.replaceAll("-----END PRIVATE KEY-----", "");
//            byte[] privateKeyBytes = Base64.decode(strtemp);
//            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//
//            KeyFactory factory = KeyFactory.getInstance("SM2");
//            PrivateKey sm2PrivateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
//            KeyPair keyPair = new KeyPair(sm2PublicKey, sm2PrivateKey);
//            X509Certificate[] chain = new X509Certificate[1];
//            chain[0] = cert;
//            if (alias == null || alias.length() <= 0)
//            {
//                alias = DnComponents.stringToBCDNString(chain[0].getSubjectDN().getName());
//            }
//            keyStore.setKeyEntry(alias, keyPair.getPrivate(), priKeyPassword, chain);
//        }
//        catch(Exception ex)
//        {
//            ex.printStackTrace();
//            alias = null;
//        }
//        finally
//        {
//            try
//            {
//                bis1.close();
//            }
//            catch(Exception ex)
//            {
//            }
//            try
//            {
//                bis2.close();
//            }
//            catch(Exception ex)
//            {
//            }
//        }
//        return alias;
//    }
}
